package bayes;

import engine.Tweet;
import engine.Tweet.Polarity;
import java.util.ArrayList;
import java.util.TreeMap;

public class BayesienMixte extends Classifieur {

    private static double K = 0.01;

    public BayesienMixte() {
        super();
    }

    @Override
    public ArrayList<Integer> determinerPolarite(ArrayList<Tweet> listOfTweet) {
        //System.out.println("Determination de la polarité de " + listOfTweet.size() + " Tweet");
        //System.out.println("Etat du dictionnaire : " + super.dictionnaire.size() + " mots");
        ArrayList<Integer> lstPolarity = new ArrayList<Integer>();
        for (Tweet tweet : listOfTweet) {
            ArrayList<String> lstWords = normalizer.normalize(tweet.getContenu());
            int meilleureClasse = bestPosterioriClass(lstWords);
            lstPolarity.add(meilleureClasse);
        }
        return lstPolarity;
    }

    private Integer bestPosterioriClass(ArrayList<String> words) {
        double scores[] = new double[Polarity.values().length - 1];
        //Calcul du posteriori pour chaque classe
        for (int i = 0; i < scores.length; i++) {
            scores[i] = 1.;
        }

        for (String word : words) {
            for (int i = 0; i < scores.length; i++) {
                scores[i] *= beta(i, word);
                //scores[i] += (tfMapsPolarity[i].containsKey(word) ? beta(i,word) : 1 - beta(i,word));
            }
        }
        double max = -Double.MAX_VALUE;
        int iMax = 0;
        for (int i = 0; i < scores.length; i++) {
            if (scores[i] * aPrioris[i] > max) {
                max = scores[i] * aPrioris[i];
                iMax = i;
            }
        }
        return iMax;
    }

    private double beta(int classe, String word) {
        TreeMap<String, Integer> currentMap = tfMapsPolarity[classe];
        double b = currentMap.containsKey(word) ? currentMap.get(word) : 0;
        b += K;
        b /= (currentMap.size() * (1 + K));
        return b;
    }
}
